package ru.poomsae.isap

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Paint
import android.graphics.Typeface
import android.os.Bundle
import android.util.TypedValue
import android.view.View
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.view.size
import com.androidnetworking.AndroidNetworking
import com.androidnetworking.common.Priority
import com.androidnetworking.error.ANError
import com.androidnetworking.interfaces.JSONObjectRequestListener
import com.example.isap_wtf.Model.ApiEndPoint
import com.example.isap_wtf.Model.Ocen
import com.example.isap_wtf.Model.ParametrsISAP
import org.json.JSONObject
import ru.poomsae.isap.Online.Freestyle.Freestyle
import ru.poomsae.isap.Online.Hapki.Hapki
import ru.poomsae.isap.Online.Para.ParaAcc
import ru.poomsae.isap.Online.SystemCut.SystemOfCut
import java.util.*
import kotlin.Comparator
import kotlin.collections.ArrayList


open class VivOcenActivity : AppCompatActivity() {
    open var kol_sud = ParametrsISAP.kol_sud
    var textSize = 50F
    var mIDHost = ParametrsISAP.idHostServer
    var idvistuplenie = ParametrsISAP.idvistuplenie
    var pokaz = ParametrsISAP.pokaz
    var arrayListOcen1 = ArrayList<Ocen>()
    var arrayListOcen2 = ArrayList<Ocen>()
    var kolOcen1 = 0
    var kolOcen2 = 0
    var numSudArray1 = ArrayList<Int>()
    var numSudArray2 = ArrayList<Int>()
    var myTimer: Timer = Timer()
    var myTimer2: Timer = Timer()
    var myTimer3: Timer = Timer()
    var numSud = ParametrsISAP.numSud
    var idvist = 0
    var sys = ParametrsISAP.sys_sud
    var sum1 = 0.0
    var sum2 = 0.0
    var tmin = 1
    var tmax = 1
    var pmin = 1
    var pmax = 1
    var connect = 0
    var idPhum = ParametrsISAP.idPhum
    lateinit var accyrVivod1: LinearLayout
    lateinit var presVivod1: LinearLayout
    lateinit var accyrVivod2: LinearLayout
    lateinit var presVivod2: LinearLayout

    lateinit var total: TextView
    lateinit var total1: TextView
    lateinit var total2: TextView

    lateinit var pokazPhumse2: TextView

    @SuppressLint("ResourceAsColor")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.vivodocen)

        accyrVivod1 = findViewById(R.id.accyrVivod1)
        presVivod1 = findViewById(R.id.presVivod1)
        accyrVivod2 = findViewById(R.id.accyrVivod2)
        presVivod2 = findViewById(R.id.presVivod2)

        total = findViewById(R.id.total)
        total1 = findViewById(R.id.total1)
        total2 = findViewById(R.id.total2)

        pokazPhumse2 = findViewById(R.id.pokazPhumse2)

        vivodOcenStart()

        val decorView = window.decorView
        val uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN
        decorView.systemUiVisibility = uiOptions
        getSupportActionBar()?.hide()
    }

    fun vivOcen() {
        val textColor = ContextCompat.getColor(this, R.color.vivodocenok)
        when(pokaz) {
            1 -> {
                accyrVivod1.removeAllViews()
                presVivod1.removeAllViews()
                arrayListOcen1.forEach {
                    val tvOcen = TextView(this)
                    tvOcen.setText((it.ocen_t / 10.toDouble()).toString())
                    tvOcen.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize)
                    tvOcen.setTextColor(textColor)
                    tvOcen.setPadding(50, 16, 50, 16)
                    tvOcen.setBackgroundResource(R.drawable.border_text)
                    accyrVivod1.addView(tvOcen)

                    val tvPres = TextView(this)
                    tvPres.setText((it.ocen_p / 10.toDouble()).toString())
                    tvPres.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize)
                    tvPres.setTextColor(textColor)
                    tvPres.setPadding(50, 16, 50, 16)
                    tvPres.setBackgroundResource(R.drawable.border_text)
                    presVivod1.addView(tvPres)
                }
            }
            2 -> {
                accyrVivod2.removeAllViews()
                presVivod2.removeAllViews()
                arrayListOcen2.forEach {
                    val tvOcen = TextView(this)
                    tvOcen.setText((it.ocen_t / 10.toDouble()).toString())
                    tvOcen.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize)
                    tvOcen.setTextColor(textColor)
                    tvOcen.setPadding(50, 16, 50, 16)
                    tvOcen.setBackgroundResource(R.drawable.border_text)
                    accyrVivod2.addView(tvOcen)

                    val tvPres = TextView(this)
                    tvPres.setText((it.ocen_p / 10.toDouble()).toString())
                    tvPres.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize)
                    tvPres.setTextColor(textColor)
                    tvPres.setPadding(50, 16, 50, 16)
                    tvPres.setBackgroundResource(R.drawable.border_text)
                    presVivod2.addView(tvPres)
                }
            }
        }

    }

    fun ocenVistup1() {
        if (pokaz == 2) {
            idvist = idvistuplenie.toInt() - 1
        } else {
            idvist = idvistuplenie.toInt()
        }
        AndroidNetworking.post("http://" + mIDHost + ApiEndPoint.VIVOCENKIA)
            .addBodyParameter("vistuplenie_idvistuplenie", idvist.toString())
            .setPriority(Priority.MEDIUM)
            .build()
            .getAsJSONObject(object : JSONObjectRequestListener {
                @SuppressLint("WrongViewCast")
                override fun onResponse(response: JSONObject?) {
                        connect = 1
                        if (connect == 1) {
                            val progressBarViv = findViewById<LinearLayout>(R.id.progressBarViv)
                            progressBarViv.visibility = View.GONE
                        }
                        arrayListOcen1.clear()
                        val jsonArray = response?.optJSONArray("ocenki")

                        if (jsonArray?.length() == 0) {
                            Toast.makeText(
                                applicationContext,
                                "Download Court List",
                                Toast.LENGTH_SHORT
                            ).show()
                        }

                        kolOcen1 = jsonArray?.length()!!

                        for (i in 0 until jsonArray?.length()!!) {
                            val jsonObject = jsonArray?.optJSONObject(i)
                            arrayListOcen1.add(
                                Ocen(
                                    jsonObject.getInt("ocenki_nomsud"),
                                    jsonObject.getInt("ocenki_t"),
                                    jsonObject.getInt("ocenki_p")
                                )
                            )
                        }
                        arrayListOcen1.forEach {
                            numSudArray1.add(it.ocen_sud)
                        }

                        for (i in 1..kol_sud.toInt()) {
                            val isContains = numSudArray1.contains(i)
                            if (isContains == false) {
                                arrayListOcen1.add(Ocen(i, 0, 0))
                            }
                        }

                        arrayListOcen1.sortWith(Comparator { c1: Ocen, c2: Ocen -> c1.ocen_sud - c2.ocen_sud })
                        vivOcen()
                        if (kol_sud.toInt() == kolOcen1) {
                            ocenEndViv1()
                        }
                    }

                @SuppressLint("WrongViewCast")
                override fun onError(anError: ANError?) {
                    val progressBarViv = findViewById<ProgressBar>(R.id.progressBarViv)
                    progressBarViv.visibility = View.VISIBLE
                    ocenVistup1()
                }
            })
    }

    fun vivodOcenStart() {
        val textColor = ContextCompat.getColor(this, R.color.vivodocenok)
        when(pokaz) {
            1 -> {
                for (i in 1..kol_sud.toInt()) {
                    val tvOcen = TextView(this)
                    tvOcen.setText("0.0")
                    tvOcen.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize)
                    tvOcen.setTextColor(textColor)
                    tvOcen.setPadding(50, 16, 50, 16)
                    tvOcen.setBackgroundResource(R.drawable.border_text)
                    accyrVivod1.addView(tvOcen)
                }

                for (i in 1..kol_sud.toInt()) {
                    val tvPres = TextView(this)
                    tvPres.setText("0.0")
                    tvPres.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize)
                    tvPres.setTextColor(textColor)
                    tvPres.setPadding(50, 16, 50, 16)
                    tvPres.setBackgroundResource(R.drawable.border_text)
                    presVivod1.addView(tvPres)
                }
                ocenStratVistup1()
            }

            2 -> {
                pokazPhumse2.visibility = View.VISIBLE
                ocenVistup1()
                for (i in 1..kol_sud.toInt()) {
                    val tvOcen = TextView(this)
                    tvOcen.setText("0.0")
                    tvOcen.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize)
                    tvOcen.setTextColor(textColor)
                    tvOcen.setPadding(50, 16, 50, 16)
                    tvOcen.setBackgroundResource(R.drawable.border_text)
                    accyrVivod1.addView(tvOcen)
                }

                for (i in 1..kol_sud.toInt()) {
                    val tvPres = TextView(this)
                    tvPres.setText("0.0")
                    tvPres.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize)
                    tvPres.setTextColor(textColor)
                    tvPres.setPadding(50, 16, 50, 16)
                    tvPres.setBackgroundResource(R.drawable.border_text)
                    presVivod1.addView(tvPres)
                }
                for (i in 1..kol_sud.toInt()) {
                    val tvOcen = TextView(this)
                    tvOcen.setText("0.0")
                    tvOcen.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize)
                    tvOcen.setTextColor(textColor)
                    tvOcen.setPadding(50, 16, 50, 16)
                    tvOcen.setBackgroundResource(R.drawable.border_text)
                    accyrVivod2.addView(tvOcen)
                }
                for (i in 1..kol_sud.toInt()) {
                    val tvPres = TextView(this)
                    tvPres.setText("0.0")
                    tvPres.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize)
                    tvPres.setTextColor(textColor)
                    tvPres.setPadding(50, 16, 50, 16)
                    tvPres.setBackgroundResource(R.drawable.border_text)
                    presVivod2.addView(tvPres)
                }
            }
        }

    }

    fun ocenEndViv1() {
        myTimer.cancel()
        val textColor = ContextCompat.getColor(this, R.color.vivodocenok)
        val maxAcy1 = arrayListOcen1.maxOf { it.ocen_t }
        val minAcy1 = arrayListOcen1.minOf { it.ocen_t }
        val maxPres1 = arrayListOcen1.maxOf { it.ocen_p }
        val minPres1 = arrayListOcen1.minOf { it.ocen_p }

        val sumT1 = arrayListOcen1.sumBy { it.ocen_t }
        val sumP1 = arrayListOcen1.sumBy { it.ocen_p }
        if (kol_sud.toInt() < 5) {
            sum1 = (sumT1 + sumP1).toDouble() / ((kol_sud.toInt()) * 10)
        } else {
            sum1 =
                (sumT1 + sumP1 - maxAcy1 - minAcy1 - maxPres1 - minPres1).toDouble() / ((kol_sud.toInt() - 2) * 10)
        }
        if (accyrVivod1.size > 0) {
            accyrVivod1.removeAllViews()
            presVivod1.removeAllViews()
            arrayListOcen1.forEach {
                val tvOcen = TextView(this)
                tvOcen.setText((it.ocen_t / 10.toDouble()).toString())
                tvOcen.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize)
                tvOcen.setTextColor(textColor)
                tvOcen.setPadding(50, 16, 50, 16)
                tvOcen.setBackgroundResource(R.drawable.border_text)
                accyrVivod1.addView(tvOcen)

                val tvPres = TextView(this)
                tvPres.setText((it.ocen_p / 10.toDouble()).toString())
                tvPres.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize)
                tvPres.setTextColor(textColor)
                tvPres.setPadding(50, 16, 50, 16)
                tvPres.setBackgroundResource(R.drawable.border_text)
                presVivod1.addView(tvPres)
                if (it.ocen_sud == numSud.toInt()) {
                    tvOcen.setTypeface(null, Typeface.BOLD)
                    tvPres.setTypeface(null, Typeface.BOLD)
                    tvOcen.setBackgroundResource(R.drawable.viv_chek_num)
                    tvPres.setBackgroundResource(R.drawable.viv_chek_num)
                }
                if (it.ocen_t == maxAcy1 && tmax == 1) {
                    tmax = tmax + 1
                    tvOcen.apply {
                        paintFlags = paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
                        text = ((it.ocen_t.toDouble() / 10).toString())
                    }
                }
                if (it.ocen_t == minAcy1 && tmin == 1) {
                    tmin = tmin + 1
                    tvOcen.apply {
                        paintFlags = paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
                        text = ((it.ocen_t.toDouble() / 10).toString())
                    }
                }
                if (it.ocen_p == maxPres1 && pmax == 1) {
                    pmax = pmax + 1
                    tvPres.apply {
                        paintFlags = paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
                        text = ((it.ocen_p.toDouble() / 10).toString())
                    }
                }
                if (it.ocen_p == minPres1 && pmin == 1) {
                    pmin = pmin + 1
                    tvPres.apply {
                        paintFlags = paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
                        text = ((it.ocen_p.toDouble() / 10).toString())
                    }
                }
            }
            if (pokaz == 1) {
                total.visibility = View.VISIBLE
                total.setText(String.format("%(.3f", sum1))
            }
        }

        if (pokaz == 2) {
            ocenStratVistup2()
        }
        vistupStartEnd()
    }

    fun ocenStratVistup2() {
        AndroidNetworking.post("http://" + mIDHost + ApiEndPoint.VIVOCENKIA)
            .addBodyParameter("vistuplenie_idvistuplenie", idvistuplenie)
            .setPriority(Priority.MEDIUM)
            .build()
            .getAsJSONObject(object : JSONObjectRequestListener {
                override fun onResponse(response: JSONObject?) {
                        val jsonArray = response?.optJSONArray("ocenki")

                        if (jsonArray?.length() == 0) {
                            Toast.makeText(
                                applicationContext,
                                "Download Court List",
                                Toast.LENGTH_SHORT
                            ).show()
                        }

                        kolOcen2 = jsonArray?.length()!!
                        if (kol_sud.toInt() == kolOcen2) {
                            ocenVistup2()
                        } else {
                            startTimer2()
                        }

                }


                override fun onError(anError: ANError?) {
                    Toast.makeText(
                        applicationContext,
                        "Error OcenStratVistup2()",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            })
    }

    fun ocenStratVistup1() {
        if (pokaz == 2) {
            idvist = idvistuplenie.toInt() - 1
        } else {
            idvist = idvistuplenie.toInt()
        }
        AndroidNetworking.post("http://" + mIDHost + ApiEndPoint.VIVOCENKIA)
            .addBodyParameter("vistuplenie_idvistuplenie", idvistuplenie)
            .setPriority(Priority.MEDIUM)
            .build()
            .getAsJSONObject(object : JSONObjectRequestListener {
                override fun onResponse(response: JSONObject?) {
                    val jsonArray = response?.optJSONArray("ocenki")

                    if(jsonArray?.length() == 0) {
                        Toast.makeText(
                            applicationContext,
                            "Download Court List",
                            Toast.LENGTH_SHORT
                        ).show()
                    }

                    try {
                    kolOcen1 = jsonArray?.length()!!
                    } catch (e: Exception) {

                    }
                    if (kol_sud.toInt() == kolOcen1) {
                        ocenVistup1()
                    } else {
                        startTimer1()
                    }
                }

                override fun onError(anError: ANError?) {
                    Toast.makeText(
                        applicationContext,
                        "Error OcenStratVistup1()",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            })
    }

    fun ocenVistup2() {
        AndroidNetworking.post("http://" + mIDHost + ApiEndPoint.VIVOCENKIA)
            .addBodyParameter("vistuplenie_idvistuplenie", idvistuplenie)
            .setPriority(Priority.MEDIUM)
            .build()
            .getAsJSONObject(object : JSONObjectRequestListener {
                override fun onResponse(response: JSONObject?) {
                    arrayListOcen2.clear()
                    val jsonArray = response?.optJSONArray("ocenki")

                    if(jsonArray?.length() == 0) {
                        Toast.makeText(
                            applicationContext,
                            "Download Court List",
                            Toast.LENGTH_SHORT
                        ).show()
                    }

                    kolOcen2 = jsonArray?.length()!!

                    for(i in 0 until jsonArray?.length()!!){
                        val jsonObject = jsonArray?.optJSONObject(i)
                        arrayListOcen2.add(
                            Ocen(jsonObject.getInt("ocenki_nomsud"),
                                jsonObject.getInt("ocenki_t"),
                                jsonObject.getInt("ocenki_p"))
                        )
                    }
                    arrayListOcen2.forEach {
                        numSudArray2.add(it.ocen_sud)
                    }

                    for (i in 1..kol_sud.toInt()) {
                        val isContains = numSudArray2.contains(i)
                        if (isContains == false) {
                            arrayListOcen2.add(Ocen(i, 0, 0))
                        }
                    }

                    arrayListOcen2.sortWith(Comparator { c1: Ocen, c2: Ocen -> c1.ocen_sud - c2.ocen_sud })
                    vivOcen()
                    if (kol_sud.toInt() == kolOcen2) {
                        ocenEndViv2()
                    }
                }

                override fun onError(anError: ANError?) {
                    Toast.makeText(
                        applicationContext,
                        "Error " + anError,
                        Toast.LENGTH_SHORT
                    ).show()
                }
            })
    }

    fun startTimer2() {
        myTimer2.schedule(object : TimerTask() {
            override fun run() {
                ocenVistup2()
            }
        }, 1, 1000)
    }

    fun startTimer1() {
        myTimer.schedule(object : TimerTask() {
            override fun run() {
                ocenVistup1()
            }
        }, 1, 1000)
    }

    fun ocenEndViv2() {
        myTimer2.cancel()
        val textColor = ContextCompat.getColor(this, R.color.vivodocenok)

        val maxAcy1 = arrayListOcen1.maxOf { it.ocen_t }
        val minAcy1 = arrayListOcen1.minOf { it.ocen_t }
        val maxPres1 = arrayListOcen1.maxOf { it.ocen_p }
        val minPres1 = arrayListOcen1.minOf { it.ocen_p }

        val sumT1 = arrayListOcen1.sumBy { it.ocen_t }
        val sumP1 = arrayListOcen1.sumBy { it.ocen_p }
        if (kol_sud.toInt() < 5) {
            val sum1 =
                (sumT1 + sumP1 - maxAcy1 - minAcy1 - maxPres1 - minPres1).toDouble() / ((kol_sud.toInt()) * 10)
        } else {
            val sum1 =
                (sumT1 + sumP1 - maxAcy1 - minAcy1 - maxPres1 - minPres1).toDouble() / ((kol_sud.toInt() - 2) * 10)
        }

        val maxAcy2 = arrayListOcen2.maxOf { it.ocen_t }
        val minAcy2 = arrayListOcen2.minOf { it.ocen_t }
        val maxPres2 = arrayListOcen2.maxOf { it.ocen_p }
        val minPres2 = arrayListOcen2.minOf { it.ocen_p }

        val sumT2 = arrayListOcen2.sumBy { it.ocen_t }
        val sumP2 = arrayListOcen2.sumBy { it.ocen_p }
        if (kol_sud.toInt() < 5) {
            sum2 = (sumT2 + sumP2).toDouble() / ((kol_sud.toInt()) * 10)
        } else {
            sum2 =
                (sumT2 + sumP2 - maxAcy2 - minAcy2 - maxPres2 - minPres2).toDouble() / ((kol_sud.toInt() - 2) * 10)
        }

        val sum = (sum1 + sum2) / 2

        accyrVivod2.removeAllViews()
        presVivod2.removeAllViews()
        tmax = 1
        tmin = 1
        pmax = 1
        pmin = 1

        arrayListOcen2.forEach {
            val tvOcen = TextView(this)
            tvOcen.setText((it.ocen_t / 10.toDouble()).toString())
            tvOcen.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize)
            tvOcen.setTextColor(textColor)
            tvOcen.setPadding(50, 16, 50, 16)
            tvOcen.setBackgroundResource(R.drawable.border_text)
            accyrVivod2.addView(tvOcen)

            val tvPres = TextView(this)
            tvPres.setText((it.ocen_p / 10.toDouble()).toString())
            tvPres.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize)
            tvPres.setTextColor(textColor)
            tvPres.setPadding(50, 16, 50, 16)
            tvPres.setBackgroundResource(R.drawable.border_text)
            presVivod2.addView(tvPres)
            if (it.ocen_sud == numSud.toInt()) {
                tvOcen.setTypeface(null, Typeface.BOLD)
                tvPres.setTypeface(null, Typeface.BOLD)
                tvOcen.setBackgroundResource(R.drawable.viv_chek_num)
                tvPres.setBackgroundResource(R.drawable.viv_chek_num)
            }
            if (it.ocen_t == maxAcy2 && tmax == 1) {
                tmax = tmax + 1
                tvOcen.apply {
                    paintFlags = paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
                    text = ((it.ocen_t.toDouble() / 10).toString())
                }
            }
            if (it.ocen_t == minAcy2 && tmin == 1) {
                tmin = tmin + 1
                tvOcen.apply {
                    paintFlags = paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
                    text = ((it.ocen_t.toDouble() / 10).toString())
                }
            }
            if (it.ocen_p == maxPres2 && pmax == 1) {
                pmax = pmax + 1
                tvPres.apply {
                    paintFlags = paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
                    text = ((it.ocen_p.toDouble() / 10).toString())
                }
            }
            if (it.ocen_p == minPres2 && pmin == 1) {
                pmin = pmin + 1
                tvPres.apply {
                    paintFlags = paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
                    text = ((it.ocen_p.toDouble() / 10).toString())
                }
            }
        }

        total.visibility = View.VISIBLE
        total1.visibility = View.VISIBLE
        total2.visibility = View.VISIBLE
        total1.setText(String.format("%.3f", sum1))
        total2.setText(String.format("%.3f", sum2))
        total.setText(String.format("%.3f", sum))

        vistupStartEnd()
    }

    fun vistupStartEnd() {
        println("vistupStartEnd() = " + idvistuplenie)
        AndroidNetworking.post("http://" + mIDHost + ApiEndPoint.VISTUPSAVA)
            .addBodyParameter("idvistuplenie", idvistuplenie)
            .addBodyParameter("numSud", numSud)
            .setPriority(Priority.MEDIUM)
            .build()
            .getAsJSONObject(object : JSONObjectRequestListener {
                override fun onResponse(response: JSONObject?) {
                    var idvistupsav = response?.getString("success")
                    println("idvistupsav =  " + idvistupsav)
                    try {
                        if (idvistupsav == "") {
                            idvistupsav = "0"
                        }
                        when(idvistupsav) {
                            "1" -> {
                                var sud = response?.getString("numSud")
                                var system = response?.getString("system")
                                if (sud!!.toInt() == numSud!!.toInt()) {
                                    when(idPhum!!) {
                                        1-15-> sys = system!!.toInt()
                                        16 -> sys = 2
                                        17, 18 -> { sys = 10; ParametrsISAP.hapki = 2 }
                                        19 -> { sys = 10; ParametrsISAP.hapki = 1 }
                                        20-> { sys = 10; ParametrsISAP.hapki = 3 }
                                    }
                                    perehod()
                                }
                            }
                            "0" -> startTimer3()
                            else ->
                            {
                                var idphumse = response?.getInt("idphumse")
                                ParametrsISAP.idvistuplenie = idvistupsav.toString()
                                var system = response?.getString("system")
                                println("idphumse  = " + idphumse)
                                when (idphumse) {
                                    1-15-> sys = system!!.toInt()
                                    16 -> sys = 2
                                    17, 18 -> { sys = 10; ParametrsISAP.hapki = 2 }
                                    19 -> { sys = 10; ParametrsISAP.hapki = 1 }
                                    20-> { sys = 10; ParametrsISAP.hapki = 3 }
                                }
                                perehod()
                            }
                        }
                    } catch(e: EnumConstantNotPresentException) {
                        println("Error!!!!")
                    }

                }

                override fun onError(anError: ANError?) {
//                    Log.d("ON ERROR", anError?.errorDetail?.toString())
                    Toast.makeText(
                        applicationContext,
                        "Error vistupStartEnd()",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            })
    }

    fun vistupEnd() {
        println("vistupEnd() = " + numSud)
        AndroidNetworking.post("http://" + mIDHost + ApiEndPoint.VISTUPSAVA)
            .addBodyParameter("idvistuplenie", idvistuplenie)
            .addBodyParameter("numSud", numSud)
            .setPriority(Priority.MEDIUM)
            .build()
            .getAsJSONObject(object : JSONObjectRequestListener {
                override fun onResponse(response: JSONObject?) {
                    var idvistupsav = response?.getString("success")
                    try {
                        if (idvistupsav == "") {
                            idvistupsav = "0"
                        }
                        when(idvistupsav) {
                            "1" -> {
                                var sud = response?.getString("numSud")
                                var system = response?.getString("system")
                                if (sud!!.toInt() == numSud!!.toInt()) {
                                    when(idPhum!!) {
                                        1-15-> sys = system!!.toInt()
                                        16 -> sys = 2
                                        17, 18 -> { sys = 10; ParametrsISAP.hapki = 2 }
                                        19 -> { sys = 10; ParametrsISAP.hapki = 1 }
                                        20-> { sys = 10; ParametrsISAP.hapki = 3 }
                                    }
                                    perehod()
                                }
                            }
                            "0" -> println("response = " + response)
                            else ->
                            {
                                var idphumse = response?.getInt("idphumse")
                                var system = response?.getString("system")
                                ParametrsISAP.idvistuplenie = idvistupsav.toString()
                                println("idphumse  = " + idphumse)
                                when (idphumse) {
                                    1-15-> sys = system!!.toInt()
                                    16 -> sys = 2
                                    17, 18 -> { sys = 10; ParametrsISAP.hapki = 2 }
                                    19 -> { sys = 10; ParametrsISAP.hapki = 1 }
                                    20-> { sys = 10; ParametrsISAP.hapki = 3 }
                                }
                                perehod()
                            }
                        }
                    } catch(e: ExceptionInInitializerError) {

                    }
                }

                override fun onError(anError: ANError?) {
                    println("ERROR = " + anError)
                }
            })
    }

    fun startTimer3() {
        myTimer3.schedule(object : TimerTask() {
            override fun run() {
                vistupEnd()
            }
        }, 1, 1000)
    }

    fun perehod() {
        myTimer3.cancel()
        when(sys) {
            1-> {
                val intent = Intent (this, SystemOfCut::class.java)
                startActivity(intent)
            }
            2-> {
                val intent = Intent (this, Freestyle::class.java)
                startActivity(intent)
            }
            3-> {
                val intent = Intent (this, ParaAcc::class.java)
                startActivity(intent)
            }
            10-> {
                val intent = Intent (this, Hapki::class.java)
                startActivity(intent)
            }
        }

    }

    override fun onBackPressed() {
        //Наше поведение...
    }

}